<template>
  <div ref="container"></div>
</template>

<script>
import * as THREE from 'three'
import { TextureLoader } from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

export default {
  mounted() {
    const container = this.$refs.container

    // 创建场景
    const scene = new THREE.Scene()

    // 创建相机
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
    camera.position.z = 5

    // 创建渲染器
    const renderer = new THREE.WebGLRenderer()
    renderer.setSize(window.innerWidth, window.innerHeight)
    container.appendChild(renderer.domElement)

    // 添加控制器
    const controls = new OrbitControls(camera, renderer.domElement)

    // 创建立方体
    const geometry = new THREE.BoxGeometry(1, 1, 1)
    const texture = new TextureLoader().load('https://threejs.org/examples/textures/crate.gif')
    const material = new THREE.MeshBasicMaterial({ map: texture })
    const mesh = new THREE.Mesh(geometry, material)
    scene.add(mesh)

    // 创建光源
    const light = new THREE.DirectionalLight(0xffffff, 1)
    light.position.set(10, 10, 10)
    scene.add(light)

    // 动画循环
    const animate = () => {
      requestAnimationFrame(animate)

      // 更新控制器
      controls.update()

      // 渲染场景
      renderer.render(scene, camera)
    }
    animate()

    // 监听窗口变化
    window.addEventListener('resize', () => {
      camera.aspect = window.innerWidth / window.innerHeight
      camera.updateProjectionMatrix()
      renderer.setSize(window.innerWidth, window.innerHeight)
    })
  }
}
</script>

<style>
  body { margin: 0; }
  canvas { width: 100%; height: 100%; }
</style>
